package com.zan.zanchat.common.common.interceptor;

import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zan.zanchat.common.common.domain.dto.RequestInfo;
import com.zan.zanchat.common.common.exception.HttpErrorEnum;
import com.zan.zanchat.common.common.utils.RequestHolder;
import com.zan.zanchat.common.user.domain.enums.BlackTypeEnum;
import com.zan.zanchat.common.user.service.cache.UserCache;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @Author Zan
 * @Create 2024/3/14 20:50
 * @Description : 获取黑名单拦截器
 */
@Component
public class BlackInterceptor implements HandlerInterceptor {

    @Resource
    private UserCache userCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从userCache中获取拉黑列表
        Map<Integer, Set<String>> blackMap = userCache.getBlackMap();
        RequestInfo requestInfo = RequestHolder.get(); // 获取uid
        // 判断是否在黑名单里面 - 判断uid
        if (inBlackList(requestInfo.getUid(), blackMap.get(BlackTypeEnum.UID.getType()))) {
            HttpErrorEnum.ACCESS_DENIED.sendHttpError(response); // 401请求
            return false; // 拦截
        }
        // 判断ip
        if (inBlackList(requestInfo.getIp(), blackMap.get(BlackTypeEnum.IP.getType()))) {
            HttpErrorEnum.ACCESS_DENIED.sendHttpError(response); // 401请求
            return false; // 拦截
        }
        return true;
    }

    private boolean inBlackList(Object target, Set<String> set) {
        if (Objects.isNull(target) || CollectionUtils.isEmpty(set)) {
            return false;
        }
        return set.contains(target.toString());
    }

}
